#!/usr/bin/python
from __future__ import with_statement
from sqlite3 import dbapi2 as sqlite
import re
import os
import sys
import time
import urllib2


#get Arrrrgs like a pirate!
flNext = False
flType = 0
cookie = "1" # your 'soba' cookie, or supply it in a -c argument, or wait for the beta to end
#user = #Your user number, or supply it in a -u argument
for arrrrg in sys.argv:
    if flNext == False:  
        if "-c" in arrrrg:
            flNext = True
            flType = 1
        elif "-u" in arrrrg:
            flNext = True
            flType = 2
    else:
        flNext = False
        if flType == 1:
            cookie = arrrrg
        elif flType == 2:
            user = int(arrrrg)
        

#os.chdir("/home/user") # if you use cron or something to run this script, this needs to be set to something.
#oh, and if you use cron, set it once per hour MAX, no need to be unreasonable
os.getcwd()
stTime = time.strftime("%Y-%m-%d %H:%M:%S")
print stTime
questLen = 60
profile = ""
connection = sqlite.connect('profile.db') #profile.db goes in the same directory that os.chdir used earlier
cursor = connection.cursor()


request = urllib2.Request(url = 'http://beta.stackoverflow.com/users/%i/myProfile.html' % (user),
                          headers = { 'Cookie': 'soba=' + cookie })
profile = urllib2.urlopen(request).read()
# print profile

# os.system('wget --no-cookies --header "Cookie: soba=%s" http://beta.stackoverflow.com/users/%i/myProfile.html' % (cookie, user))
# with open("myProfile.html") as f:
#     for line in f:
#         profile = profile + line
# f.close()
rep = re.compile('summarycount">(\d+)</div>Reputation').search(profile).group(1)
badge = re.compile('<div class="summarycount".{10,50}>(\d+)</div>.{20,100}Badges</h', re.S).search(profile).group(1)
stQuestion = re.compile('Questions</h.*?</table>', re.S).search(profile).group()
stAnswer = re.compile('Answers</h.*?</table>', re.S).search(profile).group()
mQuestion = re.compile('<a href="/questions/(\d+).*?>(.*?)</a> \((\-?\d+)\)').findall(stQuestion)
mAnswer   = re.compile('(<a href="/questions/(\d+).*?>(.*?)</a>.*?<br)').findall(stAnswer)
print "\nQuestions:"
for quest in mQuestion:
    cursor.execute('SELECT count(id), votes FROM Questions WHERE id = ' + quest[0] + ' AND type=0;')
    item = cursor.fetchone()
    if item[0] > 0:
        lastQ = (int(quest[2]) - item[1])
        if lastQ==0:lastQ=""
        cursor.execute('UPDATE Questions SET votes = %s WHERE id = %s AND type = 0' % (quest[2], quest[0]))
    else:
        cursor.execute('INSERT INTO Questions VALUES("'+quest[1]+'",'+quest[2]+',0,'+quest[0]+');')
        lastQ = "(NEW)"
    if len(quest[1]) > questLen:
        elips="..."
        nElips = 0
    else:
        elips=""
        nElips = 3
    print '%s%s %s%s' % (quest[1][:questLen].ljust(questLen+nElips," "),elips, ("("+str(quest[2])+")").ljust(5," "), lastQ)


print "\nAnswers:" + str(len(mAnswer))
for answer in mAnswer:
    mVotes = re.compile('\d+(?= vote)').search(answer[0])
    if mVotes: tVotes = mVotes.group()
    else: tVotes = "0"
    cursor.execute('SELECT count(id), votes FROM Questions WHERE id = ' + answer[1] + ' AND type=1;')
    item = cursor.fetchone()
    if item[0] > 0:
        lastQ = int(tVotes) - item[1]
        if lastQ==0:lastQ=""
        cursor.execute('UPDATE Questions SET votes = %s WHERE id = %s AND type = 1' % (tVotes, answer[1]))
    else:
        cursor.execute('INSERT INTO Questions VALUES("'+answer[2]+'",'+tVotes+',1,'+answer[1]+');')
        lastQ = "(NEW)"
    if len(answer[2]) > questLen:
        elips="..."
        nElips = 0
    else:
        elips=""
        nElips = 3
    print '%s%s %s%s' % (answer[2][:questLen].ljust(questLen+nElips," "),elips, ("("+str(tVotes)+")").ljust(5," "), lastQ)
cursor.execute('SELECT rep, badges, questions, answers , COUNT(date) FROM profile WHERE user = ' + str(user) + ' ORDER BY date DESC;')
oldData = cursor.fetchone()
if oldData[4] == 0:
    oldData = [0,0,0,0]
cursor.execute("INSERT INTO profile VALUES(%s,%s,%s,%s,'%s',%i);" % (rep,badge,len(mQuestion),len(mAnswer),stTime, user) )
print
print '%s Questions, %s new' % (len(mQuestion),(len(mQuestion) - oldData[2]))
print '%s Answers, %s new' % (len(mAnswer),(len(mAnswer) - oldData[3]))
print '%s Reputation (%+i)' % (rep, (int(rep) - oldData[0]))
print '%s Badges, %s new' % (badge, (int(badge) - oldData[1]))
connection.commit()


#os.system("espeak \"Reputation is at " + rep + " points\"")

##CREATE TABLE "main"."Questions" (
##    "Question" TEXT,
##    "votes" INTEGER,
##    "type" INTEGER,
##    "id" INTEGER
##);

##CREATE TABLE "main"."profile" (
##    "rep" INTEGER,
##    "badges" INTEGER,
##    "questions" INTEGER,
##    "answers" INTEGER,
##    "date" TEXT,
##    "user" INTEGER
##);
